package dlg.code.producer.s2;

import dlg.code.producer.ItemBuffer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

public class ProducerThread implements Runnable{

    private final ItemBuffer itemBuffer;
    private int len = 10;
    public ProducerThread(ItemBuffer itemBuffer) {
        this.itemBuffer = itemBuffer;
    }

    @Override
    public void run() {
        do {
            itemBuffer.lock.lock();
            while (itemBuffer.isFull()) {
                System.out.println(Thread.currentThread().getName() + " waiting");
                try {
                    itemBuffer.notFull.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            itemBuffer.produce(Thread.currentThread().getName() + " producing " + len--);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            itemBuffer.notEmpty.signalAll();
            itemBuffer.lock.unlock();
        } while (len >= 1);
        System.out.println(Thread.currentThread().getName() + " stop");
    }
}
